<?php

class TradeConsole{

    
    public static function addOrder($data){
        $Model = new Model();
        $OrdersModel = new OrdersModel();
        $CurrencyModel = new CurrencyModel();
        $TradeModel = new TradeModel();
        if( !isset($data['data']) || !isset($data['token']) ){
            return false;
        }
        $rsa = new Rsa();
        $signData = $data['data'];
        $signData['code'] = md5(Yaf\Registry::get('config')->application->token);
        ksort($signData);
        $check = $rsa->verify(json_encode($signData),$data['token']);
        if($check){
            $OrderData = $data['data']; 
            //判断用户是否存在
            if (!$OrderData['member_id']){
                return false;
            }
            //获取币的信息
            $currency=$CurrencyModel->getCurrencyByMarketId($OrderData['market_id']);
            if ($currency['is_lock']){
                return false;
            }
            if(!is_numeric($OrderData['price'])||!is_numeric($OrderData['num'])){
                return false;
            }
            //涨停价格限制
            if ($currency['price_down']>0&&$OrderData['price']<$currency['price_down']){
                return false;
            }
            
            //涨停价格限制
            if ($currency['price_up']>0&&$OrderData['price']>$currency['price_up']){
                return false;
            }
            //数量必须大于0
            if ($OrderData['num']<0||$OrderData['price']<0){
                return false;
            }
            //检查用户金额
            if ($CurrencyModel->checkUserMoney($OrderData['num'], $OrderData['price'], $OrderData['type'],$OrderData['member_id'], $currency)){
                return false;
            }
            $Model->startTrans();
            //计算买入需要的金额
            $trade_money=$OrderData['price']*$OrderData['num'];
            //操作账户
            if($OrderData['type']=='sell'){
                $r[]=$CurrencyModel->setUserMoney($OrderData['member_id'],$currency['currency_id'], $OrderData['num'],'dec', 'num');
                $r[]=$CurrencyModel->setUserMoney($OrderData['member_id'],$currency['currency_id'], $OrderData['num'], 'inc','forzen_num');
            }else{
                $r[]=$CurrencyModel->setUserMoney($OrderData['member_id'],$currency['trade_currency_id'], $trade_money,'dec', 'num');
                $r[]=$CurrencyModel->setUserMoney($OrderData['member_id'],$currency['trade_currency_id'], $trade_money, 'inc','forzen_num');
            }
            //挂单流程
            $r[]=$OrdersModel->thust($OrderData['member_id'],$OrderData['num'], $OrderData['price'], $OrderData['type'], $currency);
            //交易流程
            $r1[]=$TradeModel->trade($OrderData['member_id'],$currency['currency_id'],$currency['trade_currency_id'], $OrderData['type'], $OrderData['num'], $OrderData['price']);
            foreach ($r1 as $v){
                $r[]=$v;
            }
            if (in_array(false, $r)){
                $Model->rollback();
                return false;
            }else {
                $Model->commit();
                $data = array(
                    'currency_id'=>intval($currency['currency_id']),
                    'trade_currency_id'=>intval($currency['trade_currency_id']),
                    'member_id'=>intval($OrderData['member_id'])
                );
                $signData = $data;
                $signData['code']=md5(Yaf\Registry::get('config')->application->token);
                ksort($signData);
                $token = $rsa->sign(json_encode($signData));
                $data['token'] =  $token;
                return $data;
            }
        }else{
            return false;
        }
    }

    public static function delOrder($data){
        $rsa = new Rsa();
        $OrdersModel = new OrdersModel();
        if(!isset($data['data']) || !isset($data['token']) ){
            return false;
        }
        $signData = $data['data'];
        $signData['code'] = md5(Yaf\Registry::get('config')->application->token);
        ksort($signData);
        $check = $rsa->verify(json_encode($signData),$data['token']);
        if($check){
            $OrderData = $data['data']; 
            if (!$OrderData['member_id']){
                return false;
            }
            $order = $OrdersModel->getOneOrdersByMemberAndOrderId($OrderData['member_id'],$OrderData['orders_id'],array(0,1));
            if(!$order){
                return false;
            }
            $result = $OrdersModel->cancelOrdersByOrderId($order);
            if($result){
                $data = array(
                    'currency_id'=>intval($order['currency_id']),
                    'trade_currency_id'=>intval($order['currency_trade_id']),
                    'member_id'=>intval($order['member_id'])
                );
                $signData = $data;
                $signData['code']=md5(Yaf\Registry::get('config')->application->token);
                ksort($signData);
                $token = $rsa->sign(json_encode($signData));
                $data['token'] =  $token;
                return $data;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    public static function getOrder($data){
        $OrdersModel = new OrdersModel();
        $TradeModel = new TradeModel();
        $rsa = new Rsa();
        //验证数据
        $signData['currency_id'] = isset($data['currency_id'])?intval($data['currency_id']):0;
        $signData['trade_currency_id'] = isset($data['trade_currency_id'])?intval($data['trade_currency_id']):0;
        $signData['member_id'] = isset($data['member_id'])?intval($data['member_id']):0;
        $signData['code'] = md5(Yaf\Registry::get('config')->application->token);
        ksort($signData);
        $check = $rsa->verify(json_encode($signData),$data['token']);
        if($check){
            $buy = $OrdersModel->getOrders('buy',$signData['currency_id'],$signData['trade_currency_id']);
            $sell = $OrdersModel->getOrders('sell',$signData['currency_id'],$signData['trade_currency_id']);
            $history = $TradeModel->getTradesByNum(20,$signData['currency_id'],$signData['trade_currency_id'],1);
            $klist = $TradeModel->getKline(24*60,$signData['currency_id'],$signData['trade_currency_id']);
            $currency = $TradeModel->getCurrencyMessageById($signData['currency_id'],$signData['trade_currency_id']);
            $markets = $TradeModel->getMarkets();
            if($signData['member_id']>0){
                $CurrencyModel = new CurrencyModel();
                // $currency_info = array(
                //     'currency_id'=>$signData['currency_id'],
                //     'trade_currency_id'=>$signData['trade_currency_id']
                // );
                $member['member_id'] = $signData['member_id'];
                $member['currency_id'] = $signData['currency_id'];
                $member['trade_currency_id'] = $signData['trade_currency_id'];
                $member['num'] = $CurrencyModel->getUserMoney($signData['member_id'],$signData['currency_id'],'num');
                $member['forzen_num'] = $CurrencyModel->getUserMoney($signData['member_id'],$signData['currency_id'],'forzen_num');
                $member['trade_currency_num'] = $CurrencyModel->getUserMoney($signData['member_id'],$signData['trade_currency_id'],'num');
                $member['trade_currency_forzen_rmb'] = $CurrencyModel->getUserMoney($signData['member_id'],$signData['trade_currency_id'],'forzen_num');
                $member['thust'] = $OrdersModel->getOrdersByMember($signData['member_id'],$signData['currency_id'],$signData['trade_currency_id'],10);
            }else{
                $member='';
            }
            
        }else{
            $buy = '';
            $sell = '';
            $history = '';
            $klist = '';
            $currency = '';
            $member='';
            $markets='';
        }
        $rsData = array(
            'buy' => $buy,
            'sell' => $sell,
            'history' => $history,
            'klist' => $klist,
            'currency' => $currency,
            'member' => $member,
            'markets' => $markets,
        );
        return $rsData;
    }

    public static function pay(){
        Yaf\loader::import(APP_PATH.'/common/lib/easybitcoin.php');
        $CurrencyModel = new CurrencyModel();
        $CurrencyUserModel = new Model('CurrencyUser');
        $PayModel = new PayModel();
        $list = $CurrencyModel->field('rpc_user,rpc_pwd,rpc_url,port_number,currency_id')->where(array('rpc_open'=>1))->select();
        if(is_array($list)) foreach ($list as $key => $value) {
            $bitcoin = new Bitcoin($value['rpc_user'],$value['rpc_pwd'],$value['rpc_url'],$value['port_number']);
            $from = 0;
            $size = 50;
            if($bitcoin){
                $tradeList=$bitcoin->listtransactions('*', $size, $from);
                if(isset($tradeList) && is_array($tradeList) && count($tradeList)>0) foreach($tradeList as $v){
                    if($v['category']=='receive'){
                        sscanf($v['account'], "MEMBER_ID_%d", $member_id);
                        if(!$member_id) continue;
                        $data[]=array();
                        $data["currency_id"]=$value['currency_id'];//货币id写入
                        $data['member_id']=$member_id;
                        $data['url']=$v['address'];//地址
                        $data['remarks']=$v['account'];//标签
                        $data['add_time']=$v['time'];//时间
                        $data['num']=$v['amount'];//数量
                        $data['confirmations'] = $v['confirmations'];//确认数
                        $my_address = $CurrencyUserModel
                                    ->where(array('member_id'=>$data['member_id'],'currency_id'=>$data["currency_id"],'in_url'=>$data['url']))
                                    ->getField('in_url');
                        if($my_address!=$data['url']){
                            continue;
                        }
                        $CurrencyModel->startTrans();
                        $tibi_txid=$PayModel->where("txid='{$v['txid']}'")->find();
                        if(!empty($tibi_txid)){
                            //如果已经存在  而且是已经完成状态 不处理直接跳出循环
                            if($tibi_txid['status']==4){
                                continue;
                            }
                            if($v['confirmations']>2){
                                $data['status']=4;//3表示充值完成
                                $data['up_time']=$v['timereceived'];//确认时间
                                $r[] = $PayModel->where("txid='{$v['txid']}'")->save($data);//修改状态 表示已经完成
                                $r[] = $CurrencyModel->setUserMoney($data['member_id'], $data["currency_id"],$data['num'] , 'inc', 'num');//给User表加钱
                            }
                        }else{
                            $data['txid']=$v['txid'];//写入交易id号
                            if($v['confirmations']>2){
                                $data['status']=4;//3表示充值完成
                                $data['up_time']=$v['timereceived'];//确认时间
                                $r[] = $PayModel->add($data);//修改状态 表示已经完成
                                $r[] = $CurrencyModel->setUserMoney($data['member_id'], $data["currency_id"],$data['num'] , 'inc', 'num');//给User表加钱
                            }else{
                                $data['status']=0;//2表示充值中
                                $r[]  = $PayModel->add($data);
                            }
                        }
                        if(isset($r) && !in_array(false, $r)){
                            $CurrencyModel->commit();
                        }else{
                            $CurrencyModel->rollback();
                        }
                    }
                }
            }
        }
    }
}
